package com.leesche.zcsp.node.web.controller.web.user;

import com.alibaba.fastjson.JSON;
import com.leesche.zcsp.node.utils.security.QEncodeUtil;
import com.leesche.zcsp.node.utils.web.PagingResult;
import com.leesche.zcsp.node.utils.web.gernerator.TimeGreaterUilt;
import com.leesche.zcsp.node.utils.web.messge.WebResult;
import com.leesche.zcsp.node.web.constants.Constants;
import com.leesche.zcsp.node.web.controller.template.UserTemplate;
import com.leesche.zcsp.node.web.model.SysRole;
import com.leesche.zcsp.node.web.model.SysUser;
import com.leesche.zcsp.node.web.model.SysUserBusinessInfo;
import com.leesche.zcsp.node.web.model.SysUserRoleCriteria;
import com.leesche.zcsp.node.web.service.SysUserBusinessInfoService;
import com.leesche.zcsp.node.web.service.impl.data.read.*;
import com.leesche.zcsp.node.web.service.impl.data.writ.AddUserInfoCommand;
import com.leesche.zcsp.node.web.vo.ChildUser;
import com.leesche.zcsp.node.web.vo.ChildUserInfo;
import com.leesche.zcsp.node.web.vo.Principal;
import com.leesche.zcsp.node.web.vo.UserGroup;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * @author 陈立勇
 * @version V1.0
 * @Title: ChildUserController.java
 * @Description: TODO(子用户管理控制器)
 * @date 2016年9月22日 上午10:02:27
 */
@Controller
@RequestMapping("/web/childuser")
public class ChildUserController extends UserTemplate {

    private final static Logger logger = Logger
            .getLogger(ChildUserController.class);

	/*
     * @Autowired private SysUserService sysUserService;
	 */

    @Autowired
    SysUserBusinessInfoService sysUserBusinessInfoService;

    private static final String CHILDUSER_LIST_VIEW = "/web/childuser/childusers";
    private static final String CHILDUSER_ADD_VIEW = "/web/childuser/addView";
    private static final String CHILDUSER_EDIT_VIEW = "/web/childuser/editView";
    private static final String SETUP_VIEW = "/web/childuser/setupUserRoleView";

    private static final String ADDSHORTCODE_VIEW = "/web/childuser/addShortCodeView";

    @RequestMapping(value = "/childuserlist", method = RequestMethod.GET)
    public String showListView() {
        return CHILDUSER_LIST_VIEW;
    }

    @RequestMapping(value = "/childuserAddView", method = RequestMethod.GET)
    public String showAddView(HttpSession session, final Model model) {


        List<SysRole> sysRoles = sysRoleService.findChildRoleByBusinessUserID(privilegeService.getCurrentPrincipal().getUserid());

        model.addAttribute("userGroups", grneretroUserGroup(sysRoles));

        return CHILDUSER_ADD_VIEW;
    }

    @ResponseBody
    @RequestMapping(value = "/usergroup.json", method = RequestMethod.GET)
    public List<UserGroup> roleJson(HttpSession session) {

        Principal pc = privilegeService.getCurrentPrincipal();
        SysUserDto ud = new SysUserDto();
        if (pc.getNtype() == 1) {
            if (pc.getUserid() == pc.getParentid()) {
                ud.setSuperAdmin(true);
            } else {
                ud.setGeneralAdmin(true);
            }
        } else {
            ud.setUserid(pc.getUserid());
        }

        List<SysRole> sysRoles = sysRoleService
                .findSysRoleByDifferentUser(ud);

        return grneretroUserGroup(sysRoles);
    }

    /**
     * @param sysRoles model对象集合
     * @return vo对象集合
     * @Title: grneretroUserGroup
     * @Description: TODO(model对象转换vo对象)
     * @author Jerry Chen
     * @date 2016年10月11日 下午3:29:41
     */
    private List<UserGroup> grneretroUserGroup(List<SysRole> sysRoles) {
        List<UserGroup> userGruops = new ArrayList<UserGroup>();
        for (SysRole sysRole : sysRoles) {
            UserGroup userGroup = new UserGroup();
            userGroup.setUserGroupid(sysRole.getRoleid());
            userGroup.setTextCN(sysRole.getNamecn());
            userGroup.setRemark(sysRole.getRemark());
            userGroup.setTextEN(sysRole.getSname());
            userGruops.add(userGroup);
        }
        return userGruops;
    }

    /**
     * @return 系统角色列表界面
     * @Title: showSetupView
     * @Description: TODO(获取系统角色列表界面)
     * @author Jerry Chen
     * @date 2016年10月2日 下午6:22:05
     */
    @RequestMapping(value = "/{id}/setupUserGroupView", method = RequestMethod.GET)
    public String showSetupView(final @PathVariable("id") Long id,
                                final Model model) {
        try {
            model.addAttribute("childuser", super.findSysUser(id));
            model.addAttribute("sysUserRoles",
                    JSON.toJSONString(super.findUserRole(id)));
        } catch (Exception e) {
            // TODO: handle exception
            logger.error(e.getMessage(),e);
        }
        return SETUP_VIEW;
    }

    /**
     * @Title: setupUserGroup
     * @Description: TODO(设置用户角色)
     * @author Jerry Chen
     * @date 2016年10月3日 下午3:31:32
     */
    @ResponseBody
    @RequestMapping(value = "/setupUserGroup", method = RequestMethod.POST)
    public Map<String, Object> setupUserRole(final ChildUserInfo ur,
                                             HttpSession session) {

        try {

            Long userid = ur.getUserid();
            /* 设置用户的角色之前，先清空掉原来已经设置好的角色 */
            SysUserRoleCriteria criteria = new SysUserRoleCriteria();
            criteria.or().andUseridEqualTo(userid);

            sysUserRoleService.deleteByCriteria(criteria);

            Long adminid = privilegeService.getCurrentPrincipal().getUserid();

            addUserRole(ur.getRoleid(), userid, adminid);

            return WebResult.success().info("操作成功！").toMap();

        } catch (Exception e) {
            // TODO: handle exception
            logger.error(e.getMessage(),e);
            return WebResult.failure(e).toMap();
        }

    }

    @RequestMapping(value = "/{id}/childuserEditView", method = RequestMethod.GET)
    public String editView(final @PathVariable("id") long id, final Model model) {
        try {
            SysUser chileUser = super.findSysUser(id);
            int timeDifference = chileUser.getOuttime().getYear()
                    - chileUser.getCreatetime().getYear();
            model.addAttribute("timeDifference", timeDifference);
            model.addAttribute("childuser", chileUser);
        } catch (Exception e) {
            // TODO: handle exception
            logger.error(e.getMessage(),e);
        }
        return CHILDUSER_EDIT_VIEW;
    }

    @ResponseBody
    @RequestMapping(value = "/list.json", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public Map<String, Object> listJson(final QuerySysUserCondition condition,
                                        HttpSession session) {

        Long userid = privilegeService.getCurrentPrincipal().getUserid();

        /*if (pc.getNtype() == 1) {
            if (pc.getUserid() != pc.getParentid()) {
                condition.setGeneralAdmin(true);
            }
        } else {
            condition.setParentid(privilegeService.getCurrentPrincipal().getUserid());
        }*/

        condition.setGeneralAdmin(true);
        condition.setParentid(userid);
        condition.setUserid(userid);

        PagingResult<SysUserDto> pagingResult = sysUserService.findAllByPage(condition);

        for (int i = 0; i < pagingResult.getRows().size(); i++) {

            SysUserDto sysUserDto = pagingResult.getRows().get(i);

            List<SysRoleDto> sysRoles = sysUserRoleService.findUserRoleByUserid(sysUserDto.getUserid());
            StringBuffer roleNameCN = new StringBuffer();
            StringBuffer roleNameEN = new StringBuffer();

            for (int j = 0; j < sysRoles.size(); j++) {
                if (j >= 1) {
                    roleNameCN.append("、");
                    roleNameEN.append("、");
                }

                roleNameCN.append(sysRoles.get(j).getNamecn());
                roleNameEN.append(sysRoles.get(j).getSname());
            }

            pagingResult.getRows().get(i).setRoleNameCN(roleNameCN);
            pagingResult.getRows().get(i).setRoleNameEN(roleNameEN);
        }

        Map<String, Object> json = WebResult.buildOf(pagingResult).toMap();

        return json;
    }

    /**
     * @param childUser 子用户信息
     * @Title: add
     * @Description: TODO(新增子用户信息)
     * @author 陈立勇
     */
    @ResponseBody
    @RequestMapping(value = "/addchiilduserinfo", method = RequestMethod.POST)
    public Map<String, Object> add(AddUserInfoCommand childUser) {
        try {



           Principal parentUser = privilegeService.getCurrentPrincipal();

            Long parentUserID = parentUser.getUserid();

            SysUser lastChildUser = sysUserService.findLastUserByParentID(parentUserID);

            String newChildBusinessno = null;
            int newChildNtype = 0;
            if (lastChildUser != null) {
                newChildBusinessno = String.valueOf(Long.parseLong(lastChildUser.getBusinessno()) + 1);
                newChildNtype = lastChildUser.getNtype() + 1;
            } else {
                newChildBusinessno = parentUser.getBusinessno() + "01";
                newChildNtype = parentUser.getNtype() + 1;
            }

            int timeDifference = childUser.getTimeDifference() <= 0 ? 1
                    : childUser.getTimeDifference();

            SysUser newUser = new SysUser();
            newUser.setNtype(newChildNtype);
            newUser.setBusinessno(newChildBusinessno);
            newUser.setAdminid(parentUserID);
            newUser.setOuttime(TimeGreaterUilt.specifiedTime(Calendar.YEAR,
                    timeDifference));
            newUser.setPuserid(parentUserID);
            newUser.setUsername(childUser.getUsername());
            newUser.setMobile(childUser.getMobile());
            newUser.setPassword(QEncodeUtil.md5Encrypt(childUser.getPassword()));
            newUser.setRemark(childUser.getRemark());
            newUser.setProperty(childUser.getProperty());
            newUser.setState(childUser.getState());
            newUser.setCreatetime(new Date());
            //* 新增子用户
            super.addSysUserInfo(newUser);
            //* 子用户分配角色
            addUserRole(childUser.getRoleid(), newUser.getUserid(),
                    parentUserID);

            return WebResult.success().info("操作成功！").toMap();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return WebResult.failure(e).toMap();
        }

    }

    /**
     * @param user           子用户信息
     * @param timeDifference 有效使用年限
     * @Title: edit(final SysUser user, int timeDifference)
     * @Description: TODO(编辑子用户信息)
     * @author Jerry
     * @date 2016-10-17 11:14:08
     */
    @ResponseBody
    @RequestMapping(value = "/editChildUser", method = RequestMethod.POST)
    public Map<String, Object> edit(final SysUser user, int timeDifference) {
        try {

            user.setAdminid(privilegeService.getCurrentPrincipal().getUserid());
            user.setUpdatetime(new Date());

            if (timeDifference <= 0) {
                timeDifference = 1;
            }
            user.setOuttime(TimeGreaterUilt.specifiedTime(Calendar.YEAR,
                    timeDifference));

            sysUserService.updateByPrimaryKeySelective(user);

            return WebResult.success().info("操作成功！").toMap();

        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * @param userid 子用户ID
     * @Title: resetPassword(@RequestParam Long userid)
     * @Description: TODO(重置子用户密码)
     * @author Jerry
     * @date 2016-10-17 11:16:45
     */
    @ResponseBody
    @RequestMapping(value = "/resetChildUserPassword", method = RequestMethod.GET)
    public Map<String, Object> resetPassword(final @RequestParam Long userid) {
        try {

            SysUser sysUser = new SysUser();
            sysUser.setUserid(userid);
            sysUser.setAdminid(privilegeService.getCurrentPrincipal().getUserid());
            sysUser.setUpdatetime(new Date());
            sysUser.setPassword(QEncodeUtil
                    .md5Encrypt(Constants.NOTIC_DEFAULT_USER_PASSWORD));

            super.changePassword(sysUser);

            return WebResult.success().info("重置成功,初始密码为123456").toMap();

        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * @param id 子用户ID
     * @Title: delete(final long id)
     * @Description: TODO(删除子用户信息)
     * @author Jerry
     * @date 2016-10-17 11:17:56
     */
    @ResponseBody
    @RequestMapping(value = "/{id}/removeChildUser", method = RequestMethod.DELETE)
    public Map<String, Object> delete(final @PathVariable("id") long id) {
        try {

            SysUserRoleCriteria criteria = new SysUserRoleCriteria();
            criteria.or().andUseridEqualTo(id);
            sysUserRoleService.deleteByCriteria(criteria);

            sysUserService.deleteByPrimaryKey(id);

            return WebResult.success().info("操作成功！").toMap();

        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return WebResult.failure(e).toMap();
        }
    }


    @RequestMapping(value = "{userid}/showshortcode", method = RequestMethod.GET)
    public String showShortCode(final @PathVariable("userid") long userid, Model model) {
        try {
            SysUser user = new SysUser();
            user.setUserid(userid);
            user = sysUserService.findUserByUsername(user);
            model.addAttribute("user", user);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return ADDSHORTCODE_VIEW;
    }

    /**
     * @param shortCode 用户短码
     * @Title: saveUserShortCode()
     * @Description: TODO(保存用户的"短码" )
     * @author Jerry Chan
     * @date 2016/11/27 9:43
     */
    @ResponseBody
    @RequestMapping(value = "/saveshortcode", method = RequestMethod.POST)
    public Map<String, Object> saveUserShortCode(final @RequestParam String shortCode, final @RequestParam Long userid) {
        try {

            QuerySysUserCondition condition = new QuerySysUserCondition();
            //1.判断该用户是否已经存在短码;
            condition.setUserid(userid);
            condition.setCustomSQLcondition("shortCode IS NULL OR shortCode = ''");
            Integer result = sysUserService.countUserByCondition(condition);
            if (result == null || result <= 0) {
                return WebResult.failure("您的短码已经存在，不可更改。").toMap();
            }
            //2.判断该短码是否被使用
            condition.setUserid(null);
            condition.setCustomSQLcondition(null);
            condition.setShortCode(shortCode);
            result = sysUserService.countUserByCondition(condition);
            if (result > 0) {
                return WebResult.failure("短码已被占用，请使用其他短码。").toMap();
            }

            SysUser user = new SysUser();
            user.setShortcode(shortCode);
            user.setUserid(userid);
            sysUserService.updateByPrimaryKeySelective(user);

            return WebResult.success().toMap();

        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return WebResult.failure("额~ 系统繁忙！请稍后重试。").toMap();
        }
    }

    private static final String ADDBUSINESSINFO_VIEW = "/web/childuser/addBusinessInfoView";

    @RequestMapping(value = "{userid}/showUserBusinsessInfo", method = RequestMethod.GET)
    public String showUserBusinsessInfo(final @PathVariable("userid") long userid, Model model) {

        QuerySysUserBusinessInfoCondition condition = new QuerySysUserBusinessInfoCondition();
        condition.setUserid(userid);
        condition.setQueryAll(true);
        SysUserBusinessInfoDto userBusinessInfoDto = sysUserBusinessInfoService.findByCondition(condition);
        model.addAttribute("businessinfo", userBusinessInfoDto);
        model.addAttribute("userid", userid);
        return ADDBUSINESSINFO_VIEW;
    }

    /**
     * @param userid         用户ID
     * @param merchantnumber 商户号
     * @param merchantkey    商户密钥
     * @param rate           费率
     * @Title: saveUserBusinsessInfo()
     * @Description: TODO(保存用户的商业信息)
     * @author Jerry Chan
     * @date 2016/11/27 14:43
     */
    @ResponseBody
    @RequestMapping(value = "/saveUserBusinsessInfo", method = RequestMethod.POST)
    public Map<String, Object> saveUserBusinsessInfo(final Long userid, final String merchantnumber, final String merchantkey, final float rate) {
        try {

            SysUserBusinessInfo info = new SysUserBusinessInfo();
            info.setUserid(userid);
            info.setMerchantnumber(merchantnumber);
            info.setMerchantkey(merchantkey);
            info.setRate(rate);

            QuerySysUserBusinessInfoCondition condition = new QuerySysUserBusinessInfoCondition();
            condition.setUserid(userid);
            condition.setQueryAll(true);
            SysUserBusinessInfoDto userBusinessInfoDto = sysUserBusinessInfoService.findByCondition(condition);
            if (userBusinessInfoDto != null) {
                info.setBusinessinfoid(userBusinessInfoDto.getBusinessinfoid());
                sysUserBusinessInfoService.updateByPrimaryKeySelective(info);
            } else {
                sysUserBusinessInfoService.insertSelective(info);
            }
            return WebResult.success().toMap();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return WebResult.failure("额~ 系统繁忙！请稍后重试。").toMap();
        }
    }

    /**
     * @param userid         用户ID
     * @param merchantnumber 商户号
     * @param merchantkey    商户密钥
     * @param rate           费率
     * @Title: editUserBusinsessInfo()
     * @Description: TODO(编辑用户的商业信息)
     * @author Jerry Chan
     * @date 2016/11/27 14:43
     */
    @ResponseBody
    @RequestMapping(value = "/editUserBusinsessInfo", method = RequestMethod.POST)
    public Map<String, Object> editUserBusinsessInfo(final Long userid, final String merchantnumber, final String merchantkey, final float rate) {
        try {
            SysUserBusinessInfo info = new SysUserBusinessInfo();
            info.setUserid(userid);
            info.setMerchantnumber(merchantnumber);
            info.setMerchantkey(merchantkey);
            info.setRate(rate);
            sysUserBusinessInfoService.updateByPrimaryKeySelective(info);
            return WebResult.success().toMap();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return WebResult.failure("额~ 系统繁忙！请稍后重试。").toMap();
        }
    }

    /**
     * @param userid 用户ID
     * @Title: removeUserBusinsessInfo()
     * @Description: TODO(编辑用户的商业信息)
     * @author Jerry Chan
     * @date 2016/11/27 14:43
     */
    @ResponseBody
    @RequestMapping(value = "/removeUserBusinsessInfo", method = RequestMethod.POST)
    public Map<String, Object> removeUserBusinsessInfo(final Long userid) {
        try {
            sysUserBusinessInfoService.deleteByPrimaryKey(userid);
            return WebResult.success().toMap();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return WebResult.failure("额~ 系统繁忙！请稍后重试。").toMap();
        }
    }

}
